/**
 * 
 */
package cn.ad.server.web.servlet.v2.parser;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.core.util.IOUtils;

import java.io.*;

/**
 * @author Wu Chengjun
 *
 */
public class JacksonStreamSerializer implements JsonStreamSerializer {

	/**
	 * Jackson解析实例
	 */
	private ObjectMapper objectMapper = new ObjectMapper();
	
	/**
	 * 
	 */
	public JacksonStreamSerializer() {
        //配置null过滤掉
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.disable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	}
	
	/* (non-Javadoc)
	 * @see cn.ad.server.web.servlet.parser.JsonInputStreamSerializer#serialize(java.io.OutputStream, java.lang.Object)
	 */
	@Override
	public void serialize(OutputStream out, Object obj) throws JSoneSerializeException {
		 try {
			objectMapper.writeValue(out, obj);
		} catch (JsonGenerationException e) {
			throw new JSoneSerializeException(e.getMessage(), e);
		} catch (JsonMappingException e) {
			throw new JSoneSerializeException(e.getMessage(), e);
		} catch (IOException e) {
			throw new JSoneSerializeException(e.getMessage(), e);
		}
	}


	/*
	 * (non-Javadoc)
	 * @see cn.ad.server.web.servlet.parser.JsonInputStreamParser#deserialize(java.io.InputStream, java.lang.Class)
	 */
	@Override
	public <T> T deserialize(InputStream in, Class<T> cls)  throws JSoneSerializeException{
		try {
			return objectMapper.readValue(in, cls);
		} catch (JsonParseException e) {
			throw new JSoneSerializeException("parse exception: " + convertToString(in), e);
		} catch (JsonMappingException e) {
			throw new JSoneSerializeException("mapping exception: " + convertToString(in), e);
		} catch (IOException e) {
			throw new JSoneSerializeException("io exception: " + convertToString(in), e);
		}
	}

	private String convertToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        try {
            return IOUtils.toString(reader);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

		return null;
	}

}
